<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提示词管理器 - ComfyUI-xhh</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }
        
        .container {
            width: 100%;
            height: 100vh;
            background: white;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .header {
            background: #4285f4;
            color: white;
            padding: 15px 20px;
            flex-shrink: 0;
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .nav {
            display: flex;
            gap: 20px;
        }

        .nav-link {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 5px;
            transition: background-color 0.3s ease;
        }

        .nav-link:hover {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .header h1 {
            font-size: 20px;
            margin-bottom: 8px;
        }
        
        .stats {
            display: flex;
            justify-content: center;
            gap: 30px;
            margin-top: 8px;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-number {
            font-size: 18px;
            font-weight: bold;
        }
        
        .stat-label {
            font-size: 11px;
            opacity: 0.8;
        }
        
        .search-container {
            padding: 20px 24px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        
        .search-left {
            display: flex;
            gap: 10px;
            flex: 1;
        }
        
        .search-right {
            display: flex;
            align-items: center;
        }
        
        .search-input {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }
        
        .search-input:focus {
            outline: none;
            border-color: #4285f4;
            box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.1), 0 4px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .search-input::placeholder {
            color: #9e9e9e;
            font-style: italic;
        }
        
        .search-btn {
            padding: 10px 20px;
            background: linear-gradient(135deg, #4285f4 0%, #34a853 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(66, 133, 244, 0.2);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .search-btn:hover {
            background: linear-gradient(135deg, #3367d6 0%, #2d8f47 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(66, 133, 244, 0.3);
        }
        
        .search-btn:before {
            content: '🔍';
            font-size: 16px;
        }
        
        .tab-switch {
            display: flex;
            background: #e9ecef;
            border-radius: 6px;
            padding: 2px;
            gap: 2px;
        }
        
        .tab-switch-btn {
            padding: 8px 16px;
            border: none;
            background: transparent;
            color: #6c757d;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }
        
        .tab-switch-btn.active {
            background: white;
            color: #4285f4;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .tab-switch-btn:hover:not(.active) {
            color: #495057;
        }
        
        .content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            transition: all 0.3s ease;
        }
        
        .prompts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
            flex: 1;
            overflow-y: auto;
        }
        
        .prompt-card {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
            transition: transform 0.2s, box-shadow 0.2s;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            min-height: 320px;
            max-height: 400px;
        }
        
        .prompt-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .prompt-card.selected {
            border-color: #4285f4;
            background: #f8f9ff;
        }
        
        .image-container {
            position: relative;
            width: 100%;
            height: 180px;
            background: #f8f9fa;
            overflow: hidden;
            display: flex;
            flex-shrink: 0;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .prompt-image {
            width: 100%;
            height: 100%;
            object-fit: contain;
            cursor: pointer;
            display: block;
            background: #f8f9fa;
        }
        
        .image-placeholder {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
            color: #6c757d;
            font-size: 14px;
            border: 2px dashed #dee2e6;
        }
        
        .prompt-content {
            padding: 15px;
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }
        
        .prompt-text {
            font-size: 14px;
            line-height: 1.4;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            cursor: pointer;
            margin-bottom: 10px;
            min-height: 1.4em;
            flex-shrink: 1;
            word-break: break-word;
            white-space: nowrap;
        }
        
        .prompt-text:hover {
            color: #4285f4;
        }
        
        .prompt-time {
            font-size: 11px;
            color: #666;
            margin-bottom: 8px;
            opacity: 0.8;
        }
        
        .prompt-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-top: 1px solid #f0f0f0;
            flex-shrink: 0;
            min-height: 36px;
            margin-top: auto;
            flex-wrap: wrap;
            gap: 4px;
        }
        
        .prompt-actions-left {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
        }
        
        .prompt-actions-right {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
        }
        
        .copy-btn {
            background: #4285f4;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            white-space: nowrap;
            flex-shrink: 0;
            min-width: 40px;
        }
        
        .copy-btn:hover {
            background: #3367d6;
        }
        
        .use-btn {
            background: #4caf50;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            white-space: nowrap;
            flex-shrink: 0;
            min-width: 40px;
        }
        
        .use-btn:hover {
            background: #45a049;
        }
        
        .edit-btn {
            background: #ff9800;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            white-space: nowrap;
            flex-shrink: 0;
            min-width: 40px;
        }
        
        .edit-btn:hover {
            background: #e68900;
        }
        
        .favorite-btn {
            background: transparent;
            border: 1px solid #ddd;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
            flex-shrink: 0;
            transition: all 0.2s;
            min-width: 40px;
        }
        
        .favorite-btn:hover {
            background: #f8f9fa;
            border-color: #ff6b6b;
        }
        
        .favorite-btn.favorited {
            background: #ff6b6b;
            border-color: #ff6b6b;
            color: white;
        }
        
        .favorite-btn.favorited:hover {
            background: #ff5252;
            border-color: #ff5252;
        }
        
        .delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 11px;
            white-space: nowrap;
            flex-shrink: 0;
            min-width: 40px;
        }
        
        /* 删除确认弹窗样式 */
        .delete-confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        
        .delete-confirm-modal.show {
            opacity: 1;
            visibility: visible;
        }
        
        .delete-confirm-content {
            background: white;
            border-radius: 12px;
            padding: 32px;
            max-width: 400px;
            width: 90%;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.9);
            transition: transform 0.3s ease;
        }
        
        .delete-confirm-modal.show .delete-confirm-content {
            transform: scale(1);
        }
        
        .delete-confirm-icon {
            font-size: 48px;
            margin-bottom: 16px;
            color: #ff4757;
        }
        
        .delete-confirm-title {
            font-size: 20px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 12px;
        }
        
        .delete-confirm-message {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 24px;
            line-height: 1.5;
        }
        
        .delete-confirm-buttons {
            display: flex;
            gap: 12px;
            justify-content: center;
        }
        
        .delete-confirm-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 80px;
        }
        
        .delete-confirm-btn.cancel {
            background: #f8f9fa;
            color: #6c757d;
            border: 1px solid #e9ecef;
        }
        
        .delete-confirm-btn.cancel:hover {
            background: #e9ecef;
            color: #495057;
        }
        
        .delete-confirm-btn.confirm {
            background: #ff4757;
            color: white;
        }
        
        .delete-confirm-btn.confirm:hover {
            background: #ff3742;
            transform: translateY(-1px);
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: auto;
            padding: 15px 0;
            border-top: 1px solid #e0e0e0;
            background: white;
            flex-shrink: 0;
            flex-wrap: wrap;
        }
        
        .pagination-controls {
            display: flex;
            align-items: center;
            gap: 15px;
            margin: 0 20px;
        }
        
        .page-size-control {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .page-size-control label {
            font-size: 14px;
            color: #666;
        }
        
        .page-size-control select {
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .page-jump-control {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .page-jump-control label {
            font-size: 14px;
            color: #666;
        }
        
        .page-jump-control input {
            width: 60px;
            padding: 4px 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            text-align: center;
        }
        
        .page-jump-control button {
            padding: 4px 12px;
            background: #4285f4;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .page-jump-control button:hover {
            background: #3367d6;
        }
        
        .pagination button {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .pagination button:hover:not(:disabled) {
            background: #f0f0f0;
        }
        
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination .current-page {
            background: #4285f4;
            color: white;
            border-color: #4285f4;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .empty-state h3 {
            margin-bottom: 10px;
            color: #333;
        }
        
         .loading {
             text-align: center;
             padding: 40px;
             color: #666;
             flex: 1;
             display: flex;
             justify-content: center;
             align-items: center;
         }
         
        /* 图片浏览模态框样式 */
        .image-gallery-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.95);
        }

        .gallery-header {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 60px;
            background: rgba(0,0,0,0.8);
            color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            z-index: 1001;
        }

        .gallery-header h3 {
            margin: 0;
            font-size: 18px;
        }

        .gallery-close {
            font-size: 30px;
            cursor: pointer;
            color: #fff;
        }

        .gallery-close:hover {
            color: #ccc;
        }

        .gallery-container {
            display: flex;
            height: 100%;
            padding-top: 60px;
        }

        /* 左侧缩略图列表 */
        .thumbnail-sidebar {
            width: 200px;
            background: rgba(0,0,0,0.7);
            overflow-y: auto;
            padding: 20px 10px;
            scroll-behavior: smooth;
        }

        .thumbnail-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .thumbnail-item {
            width: 100%;
            height: 120px;
            border: 2px solid transparent;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }

        .thumbnail-item:hover {
            border-color: #4285f4;
            transform: scale(1.05);
        }

        .thumbnail-item.active {
            border-color: #4285f4;
            box-shadow: 0 0 10px rgba(66, 133, 244, 0.5);
        }

        .thumbnail-item img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: #f0f0f0;
            border: 1px solid #ccc;
        }

        /* 中间主图片区域 */
        .main-image-area {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            background: #000;
            min-height: 400px;
            width: 100%;
        }

        .nav-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0,0,0,0.7);
            color: white;
            border: none;
            font-size: 30px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            cursor: pointer;
            z-index: 100;
            transition: all 0.3s ease;
        }

        .nav-btn:hover {
            background: rgba(0,0,0,0.9);
            transform: translateY(-50%) scale(1.1);
        }

        .prev-btn {
            left: 20px;
        }

        .next-btn {
            right: 20px;
        }

        .image-display {
            flex: 1;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 400px;
        }

        .main-image {
            max-width: 100%;
            height: 100vh;
            object-fit: contain;
            border-radius: 8px;
            display: block !important;
            width: auto;
            visibility: visible !important;
            opacity: 1 !important;
            cursor: grab;
            transition: transform 0.3s ease;
        }
        
        .main-image:active {
            cursor: grabbing;
        }
        
        .main-image.zoom-mode {
            cursor: zoom-in;
        }
        
        .main-image.zoom-mode.zoomed {
            cursor: zoom-out;
        }
        
        .main-image.zoomed {
            transform: scale(1.5);
        }
        
        /* 模式切换按钮 */
        .mode-controls {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            gap: 10px;
        }
        
        .mode-btn {
            padding: 8px 16px;
            background: rgba(0,0,0,0.7);
            color: white;
            border: 1px solid #666;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }
        
        .mode-btn:hover {
            background: rgba(0,0,0,0.9);
            border-color: #4285f4;
        }
        
        .mode-btn.active {
            background: #4285f4;
            border-color: #4285f4;
        }
        
        /* 缩放和拖拽模式 */
        .image-display.manual-mode {
            overflow: hidden;
        }
        
        .image-display.manual-mode .main-image {
            cursor: zoom-in;
        }
        
        .image-display.manual-mode .main-image.zoomed {
            cursor: zoom-out;
        }
        
        /* 滚动模式样式 */
        .image-display:not(.manual-mode) {
            overflow: visible;
        }
        
        .image-display:not(.manual-mode) .main-image {
            cursor: default;
        }

        .image-info {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .delete-image-btn {
            background: #ff4757;
            color: white;
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        .delete-image-btn:hover {
            background: #ff3742;
            transform: scale(1.1);
        }

        /* 右侧提示词信息 */
        .prompt-info-sidebar {
            width: 300px;
            background: rgba(0,0,0,0.7);
            padding: 20px;
            overflow-y: auto;
        }

        .prompt-info-sidebar h4 {
            color: #4285f4;
            margin-bottom: 15px;
            font-size: 16px;
        }

        .prompt-text {
            color: #ccc;
            line-height: 1.6;
            font-size: 14px;
            white-space: pre-wrap;
        }
        
        /* 图片浏览界面的提示词样式 */
        #currentPromptText {
            color: #ccc;
            line-height: 1.6;
            font-size: 14px;
            white-space: pre-wrap;
            overflow: visible !important;
            text-overflow: unset !important;
            display: block !important;
            word-wrap: break-word;
            word-break: break-all;
        }
        
        /* 竖屏模式优化 */
        @media (max-width: 768px) {
            .prompt-actions {
                flex-direction: column;
                align-items: stretch;
                gap: 8px;
            }
            
            .prompt-actions-left,
            .prompt-actions-right {
                justify-content: center;
                width: 100%;
            }
            
            .prompt-text {
                font-size: 13px;
                line-height: 1.3;
            }
            
            .copy-btn,
            .edit-btn,
            .favorite-btn,
            .delete-btn,
            .use-btn {
                flex: 1;
                min-width: 60px;
                font-size: 10px;
                padding: 6px 4px;
            }
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-content">
                <div class="header-left">
                    <h1>提示词管理器</h1>
                    <div class="stats">
                        <div class="stat-item">
                            <div class="stat-number" id="totalCount">0</div>
                            <div class="stat-label">总提示词</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-number" id="favoriteCount">0</div>
                            <div class="stat-label">收藏</div>
                        </div>
                    </div>
                </div>
                <div class="nav">
                    <a href="/xhh/manager/index.html" class="nav-link">🏠 首页</a>
                    <a href="/xhh/lora-manager" class="nav-link">🎯 LoRA管理</a>
                    <a href="/xhh/manager/categories.html" class="nav-link">📂 基础分类</a>
                </div>
            </div>
        </div>
        
        <div class="content">
            <div class="search-container">
                <div class="search-left">
                    <input type="text" id="searchInput" placeholder="搜索提示词..." class="search-input">
                    <button id="searchBtn" class="search-btn">搜索</button>
                </div>
                <div class="search-right">
                    <div class="tab-switch">
                        <button class="tab-switch-btn active" id="allTab">全部</button>
                        <button class="tab-switch-btn" id="favoriteTab">收藏</button>
                    </div>
                </div>
            </div>
            
            <div id="loading" class="loading">加载中...</div>
            <div id="promptsContainer" class="prompts-grid" style="display: none;"></div>
            <div id="emptyState" class="empty-state" style="display: none;">
                <h3>暂无提示词数据</h3>
                <p>请先添加一些提示词数据</p>
            </div>
             <div id="pagination" class="pagination" style="display: none;"></div>
         </div>
     </div>
     
     <!-- 图片浏览模态框 -->
     <div id="imageModal" class="image-gallery-modal">
         <div class="gallery-header">
             <h3 id="galleryTitle">图片浏览</h3>
             <span class="gallery-close" id="galleryClose">&times;</span>
         </div>
         <div class="gallery-container">
             <!-- 左侧缩略图列表 -->
             <div class="thumbnail-sidebar">
                 <div class="thumbnail-list" id="thumbnailList">
                     <!-- 缩略图将在这里动态生成 -->
                 </div>
             </div>
             
             <!-- 中间主图片区域 -->
             <div class="main-image-area">
                 <button class="nav-btn prev-btn" id="prevBtn">‹</button>
                 <div class="image-display">
                     <img id="mainImage" class="main-image" src="" alt="">
                     <div class="image-info">
                         <span id="imageCounter">1 / 1</span>
                     </div>
                 </div>
                 <button class="nav-btn next-btn" id="nextBtn">›</button>
             </div>
             
             <!-- 右侧提示词信息 -->
             <div class="prompt-info-sidebar">
                 <h4>提示词信息</h4>
                 <div id="promptText" class="prompt-text"></div>
             </div>
         </div>
     </div>

    <script>
        class PromptManager {
            constructor() {
                this.prompts = [];
                this.filteredPrompts = [];
                this.currentPage = 1;
                this.itemsPerPage = 12;
                this.searchQuery = '';
                this.currentTab = 'all';
                this.totalCount = 0;
                this.totalPages = 0;
                
                this.init();
            }

            async init() {
                console.log('🚀 PromptManager 初始化开始...');
                await this.loadPrompts();
                this.bindEvents();
                console.log('✅ PromptManager 初始化完成');
            }

            async loadPrompts() {
                try {
                    console.log('🔄 开始加载提示词数据...');
                    
                    const params = new URLSearchParams({
                        page: this.currentPage,
                        per_page: this.itemsPerPage
                    });
                    
                    if (this.searchQuery) {
                        params.append('search', this.searchQuery);
                    }
                    
                    if (this.currentTab === 'favorite') {
                        params.append('favorite_only', 'true');
                    }
                    
                    console.log('🌐 正在从API获取数据...', params.toString());
                    const response = await fetch(`/api/xhh/prompts?${params.toString()}`);
                    console.log(`📡 API响应状态: ${response.status} ${response.statusText}`);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const result = await response.json();
                    console.log('📊 API返回数据:', result);
                    
                    // 处理新的数据结构
                    if (result.success && result.data) {
                        this.prompts = result.data.prompts || [];
                        this.totalCount = result.data.pagination?.total || 0;
                        this.totalPages = result.data.pagination?.pages || 0;
                    } else {
                        // 降级处理旧格式
                        this.prompts = result.prompts || [];
                        this.totalCount = result.total_count || 0;
                        this.totalPages = result.total_pages || 0;
                    }
                    
                    this.render();
                    
                } catch (error) {
                    console.error('❌ 加载提示词失败:', error);
                    this.showError('加载提示词失败: ' + error.message);
                }
            }

            render() {
                const container = document.getElementById('promptsContainer');
                const loading = document.getElementById('loading');
                const emptyState = document.getElementById('emptyState');
                const pagination = document.getElementById('pagination');
                
                // 更新统计信息
                document.getElementById('totalCount').textContent = this.totalCount;
                document.getElementById('favoriteCount').textContent = this.prompts.filter(p => p.is_favorite).length;
                
                if (this.prompts.length === 0) {
                    loading.style.display = 'none';
                    container.style.display = 'none';
                    emptyState.style.display = 'flex';
                    pagination.style.display = 'none';
                    return;
                }
                
                loading.style.display = 'none';
                emptyState.style.display = 'none';
                container.style.display = 'grid';
                pagination.style.display = 'flex';
                
                 // 渲染卡片
                 container.innerHTML = this.prompts.map(prompt => `
                     <div class="prompt-card" data-id="${prompt.id}">
                         <div class="image-container">
                             ${prompt.image_data ? 
                                 `<img src="${prompt.image_data}" alt="Prompt Image" class="prompt-image" data-original="${prompt.original_image || prompt.image_data}" onclick="promptManager.showFullImage('${prompt.original_image || prompt.image_data}', ${prompt.id})" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">` : 
                                 ''
                             }
                             <div class="image-placeholder" style="display: ${prompt.image_data ? 'none' : 'flex'};">
                                 <span>无图片</span>
                             </div>
                         </div>
                        <div class="prompt-content">
                            <div class="prompt-text" data-prompt-id="${prompt.id}" title="点击复制提示词">
                                ${this.escapeHtml(prompt.text)}
                            </div>
                            <div class="prompt-time">
                                ${this.formatTime(prompt.created_at)}
                            </div>
                            <div class="prompt-actions">
                                <div class="prompt-actions-left">
                                    <button class="copy-btn" data-prompt-id="${prompt.id}">复制</button>
                                    <button class="use-btn" data-prompt-id="${prompt.id}">使用</button>
                                    <button class="edit-btn" data-prompt-id="${prompt.id}">编辑</button>
                                    <button class="favorite-btn ${prompt.is_favorite ? 'favorited' : ''}" data-prompt-id="${prompt.id}" title="${prompt.is_favorite ? '取消收藏' : '添加收藏'}">
                                        ${prompt.is_favorite ? '❤️' : '🤍'}
                                    </button>
                                </div>
                                <div class="prompt-actions-right">
                                    <button class="delete-btn" data-prompt-id="${prompt.id}">删除</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('');
                
                // 渲染分页
                this.renderPagination();
            }

            renderPagination() {
                const pagination = document.getElementById('pagination');
                
                if (this.totalPages <= 1) {
                    pagination.style.display = 'none';
                    return;
                }
                
                let paginationHTML = '';
                
                // 分页控制区域
                paginationHTML += `
                    <div class="pagination-controls">
                        <div class="page-size-control">
                            <label>每页显示:</label>
                            <select id="pageSizeSelect" onchange="promptManager.changePageSize(this.value)">
                                <option value="6" ${this.itemsPerPage === 6 ? 'selected' : ''}>6</option>
                                <option value="12" ${this.itemsPerPage === 12 ? 'selected' : ''}>12</option>
                                <option value="24" ${this.itemsPerPage === 24 ? 'selected' : ''}>24</option>
                                <option value="48" ${this.itemsPerPage === 48 ? 'selected' : ''}>48</option>
                            </select>
                        </div>
                        <div class="page-jump-control">
                            <label>跳转到:</label>
                            <input type="number" id="pageJumpInput" min="1" max="${this.totalPages}" value="${this.currentPage}">
                            <button onclick="promptManager.jumpToPage()">跳转</button>
                        </div>
                    </div>
                `;
                
                // 上一页按钮
                paginationHTML += `<button ${this.currentPage <= 1 ? 'disabled' : ''} onclick="promptManager.goToPage(${this.currentPage - 1})">上一页</button>`;
                
                // 页码按钮
                const startPage = Math.max(1, this.currentPage - 2);
                const endPage = Math.min(this.totalPages, this.currentPage + 2);
                
                if (startPage > 1) {
                    paginationHTML += `<button onclick="promptManager.goToPage(1)">1</button>`;
                    if (startPage > 2) {
                        paginationHTML += `<span>...</span>`;
                    }
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    paginationHTML += `<button class="${i === this.currentPage ? 'current-page' : ''}" onclick="promptManager.goToPage(${i})">${i}</button>`;
                }
                
                if (endPage < this.totalPages) {
                    if (endPage < this.totalPages - 1) {
                        paginationHTML += `<span>...</span>`;
                    }
                    paginationHTML += `<button onclick="promptManager.goToPage(${this.totalPages})">${this.totalPages}</button>`;
                }
                
                // 下一页按钮
                paginationHTML += `<button ${this.currentPage >= this.totalPages ? 'disabled' : ''} onclick="promptManager.goToPage(${this.currentPage + 1})">下一页</button>`;
                
                pagination.innerHTML = paginationHTML;
            }

            async goToPage(page) {
                if (page < 1 || page > this.totalPages || page === this.currentPage) return;
                
                this.currentPage = page;
                await this.loadPrompts();
            }
            
            async changePageSize(newSize) {
                const size = parseInt(newSize);
                if (size !== this.itemsPerPage) {
                    this.itemsPerPage = size;
                    this.currentPage = 1; // 重置到第一页
                    await this.loadPrompts();
                }
            }
            
            async jumpToPage() {
                const input = document.getElementById('pageJumpInput');
                const page = parseInt(input.value);
                
                if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
                    this.currentPage = page;
                    await this.loadPrompts();
                } else {
                    // 如果输入无效，重置为当前页
                    input.value = this.currentPage;
                }
            }

            bindEvents() {
                // 搜索功能
                document.getElementById('searchBtn').addEventListener('click', () => {
                    this.searchQuery = document.getElementById('searchInput').value.trim();
                    this.currentPage = 1;
                    this.loadPrompts();
                });
                
                document.getElementById('searchInput').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.searchQuery = e.target.value.trim();
                        this.currentPage = 1;
                        this.loadPrompts();
                    }
                });
                
                // 标签页切换
                document.getElementById('allTab').addEventListener('click', () => {
                    this.currentTab = 'all';
                    this.currentPage = 1;
                    this.updateTabButtons();
                    this.loadPrompts();
                });
                
                document.getElementById('favoriteTab').addEventListener('click', () => {
                    this.currentTab = 'favorite';
                    this.currentPage = 1;
                    this.updateTabButtons();
                    this.loadPrompts();
                });
                
                // 卡片点击事件
                document.addEventListener('click', (e) => {
                    if (e.target.classList.contains('copy-btn')) {
                        this.copyPrompt(e.target.dataset.promptId);
                    } else if (e.target.classList.contains('use-btn')) {
                        this.usePrompt(e.target.dataset.promptId);
                    } else if (e.target.classList.contains('edit-btn')) {
                        this.editPrompt(e.target.dataset.promptId);
                    } else if (e.target.classList.contains('favorite-btn')) {
                        this.toggleFavorite(e.target.dataset.promptId);
                    } else if (e.target.classList.contains('delete-btn')) {
                        this.deletePrompt(e.target.dataset.promptId);
                    } else if (e.target.classList.contains('prompt-text')) {
                        this.copyPrompt(e.target.dataset.promptId);
                    }
                });
            }

            updateTabButtons() {
                document.getElementById('allTab').classList.toggle('active', this.currentTab === 'all');
                document.getElementById('favoriteTab').classList.toggle('active', this.currentTab === 'favorite');
            }

            async copyPrompt(promptId) {
                const prompt = this.prompts.find(p => p.id == promptId);
                if (!prompt) return;
                
                try {
                    await navigator.clipboard.writeText(prompt.text);
                    this.showMessage('提示词已复制到剪贴板');
                } catch (error) {
                    console.error('复制失败:', error);
                    this.showMessage('复制失败，请手动复制');
                }
            }

            usePrompt(promptId) {
                const prompt = this.prompts.find(p => p.id == promptId);
                if (!prompt) return;
                
                console.log('🎯 使用提示词:', prompt.text);
                
                // 向父窗口发送消息
                if (window.parent && window.parent !== window) {
                    window.parent.postMessage({
                        type: 'use_prompt',
                        prompt: prompt.text,
                        promptId: promptId
                    }, '*');
                    this.showMessage('提示词已发送到ComfyUI');
                } else {
                    // 降级到复制到剪贴板
                    this.copyPrompt(promptId);
                    this.showMessage('提示词已复制到剪贴板');
                }
            }

            async editPrompt(promptId) {
                const prompt = this.prompts.find(p => p.id == promptId);
                if (!prompt) return;
                
                // 创建自定义编辑对话框
                this.showEditDialog(prompt);
            }
            
            showEditDialog(prompt) {
                // 创建模态对话框
                const modal = document.createElement('div');
                modal.className = 'edit-modal';
                modal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 10000;
                `;
                
                // 创建对话框内容
                const dialog = document.createElement('div');
                dialog.style.cssText = `
                    background: white;
                    border-radius: 8px;
                    padding: 20px;
                    width: 80%;
                    max-width: 600px;
                    max-height: 80vh;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                    display: flex;
                    flex-direction: column;
                `;
                
                // 标题
                const title = document.createElement('h3');
                title.textContent = '编辑提示词';
                title.style.cssText = `
                    margin: 0 0 15px 0;
                    color: #333;
                    font-size: 18px;
                `;
                
                // 文本区域
                const textarea = document.createElement('textarea');
                textarea.value = prompt.text;
                textarea.style.cssText = `
                    width: 100%;
                    height: 200px;
                    padding: 12px;
                    border: 2px solid #ddd;
                    border-radius: 4px;
                    font-size: 14px;
                    font-family: inherit;
                    resize: vertical;
                    box-sizing: border-box;
                `;
                textarea.addEventListener('focus', () => {
                    textarea.style.borderColor = '#4285f4';
                });
                textarea.addEventListener('blur', () => {
                    textarea.style.borderColor = '#ddd';
                });
                
                // 按钮容器
                const buttonContainer = document.createElement('div');
                buttonContainer.style.cssText = `
                    display: flex;
                    justify-content: flex-end;
                    gap: 10px;
                    margin-top: 15px;
                `;
                
                // 取消按钮
                const cancelBtn = document.createElement('button');
                cancelBtn.textContent = '取消';
                cancelBtn.style.cssText = `
                    padding: 8px 16px;
                    border: 1px solid #ddd;
                    background: white;
                    color: #666;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                `;
                cancelBtn.addEventListener('click', () => {
                    document.body.removeChild(modal);
                });
                
                // 确定按钮
                const confirmBtn = document.createElement('button');
                confirmBtn.textContent = '确定';
                confirmBtn.style.cssText = `
                    padding: 8px 16px;
                    border: none;
                    background: #4285f4;
                    color: white;
                    border-radius: 4px;
                    cursor: pointer;
                    font-size: 14px;
                `;
                
                // 确定按钮事件
                confirmBtn.addEventListener('click', async () => {
                    const newText = textarea.value.trim();
                    if (newText === prompt.text) {
                        document.body.removeChild(modal);
                        return;
                    }
                    
                    if (!newText) {
                        this.showMessage('提示词不能为空');
                        return;
                    }
                    
                    try {
                        const response = await fetch(`/api/xhh/prompts/${prompt.id}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                text: newText
                            })
                        });
                        
                        if (response.ok) {
                            this.showMessage('提示词已更新');
                            this.loadPrompts();
                            document.body.removeChild(modal);
                        } else {
                            throw new Error('更新失败');
                        }
                    } catch (error) {
                        console.error('更新提示词失败:', error);
                        this.showMessage('更新失败: ' + error.message);
                    }
                });
                
                // 组装对话框
                buttonContainer.appendChild(cancelBtn);
                buttonContainer.appendChild(confirmBtn);
                
                dialog.appendChild(title);
                dialog.appendChild(textarea);
                dialog.appendChild(buttonContainer);
                
                modal.appendChild(dialog);
                document.body.appendChild(modal);
                
                // 点击背景关闭
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) {
                        document.body.removeChild(modal);
                    }
                });
                
                // 键盘事件
                const handleKeydown = (e) => {
                    if (e.key === 'Escape') {
                        document.body.removeChild(modal);
                        document.removeEventListener('keydown', handleKeydown);
                    }
                };
                document.addEventListener('keydown', handleKeydown);
                
                // 自动聚焦到文本框
                setTimeout(() => {
                    textarea.focus();
                    textarea.select();
                }, 100);
            }

            async toggleFavorite(promptId) {
                const prompt = this.prompts.find(p => p.id == promptId);
                if (!prompt) return;
                
                try {
                    const response = await fetch(`/api/xhh/prompts/${promptId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            is_favorite: !prompt.is_favorite
                        })
                    });
                    
                    if (response.ok) {
                        this.showMessage(prompt.is_favorite ? '已取消收藏' : '已添加收藏');
                        this.loadPrompts();
                    } else {
                        throw new Error('操作失败');
                    }
                } catch (error) {
                    console.error('收藏操作失败:', error);
                    this.showMessage('操作失败: ' + error.message);
                }
            }

            async deletePrompt(promptId) {
                console.log('🗑️ 开始删除提示词:', promptId);
                
                // 显示自定义确认弹窗
                const confirmed = await this.showDeleteConfirm();
                if (!confirmed) return;
                
                try {
                    const response = await fetch(`/api/xhh/prompts/${promptId}`, {
                        method: 'DELETE'
                    });
                    
                    console.log('🗑️ 删除请求响应状态:', response.status);
                    console.log('🗑️ 删除请求响应内容:', await response.text());
                    
                    if (response.ok) {
                        this.showMessage('提示词已删除');
                        this.loadPrompts();
                    } else {
                        throw new Error('删除失败');
                    }
                } catch (error) {
                    console.error('删除提示词失败:', error);
                    this.showMessage('删除失败: ' + error.message);
                }
            }
            
            showDeleteConfirm() {
                return new Promise((resolve) => {
                    // 创建确认弹窗
                    const modal = document.createElement('div');
                    modal.className = 'delete-confirm-modal';
                    modal.innerHTML = `
                        <div class="delete-confirm-content">
                            <div class="delete-confirm-icon">🗑️</div>
                            <div class="delete-confirm-title">确认删除</div>
                            <div class="delete-confirm-message">确定要删除这个提示词吗？<br>删除后无法恢复。</div>
                            <div class="delete-confirm-buttons">
                                <button class="delete-confirm-btn cancel">取消</button>
                                <button class="delete-confirm-btn confirm">删除</button>
                            </div>
                        </div>
                    `;
                    
                    // 添加到页面
                    document.body.appendChild(modal);
                    
                    // 显示弹窗
                    setTimeout(() => {
                        modal.classList.add('show');
                    }, 10);
                    
                    // 绑定事件
                    const cancelBtn = modal.querySelector('.cancel');
                    const confirmBtn = modal.querySelector('.confirm');
                    
                    const closeModal = (result) => {
                        modal.classList.remove('show');
                        setTimeout(() => {
                            document.body.removeChild(modal);
                            resolve(result);
                        }, 300);
                    };
                    
                    cancelBtn.onclick = () => closeModal(false);
                    confirmBtn.onclick = () => closeModal(true);
                    
                    // 点击背景关闭
                    modal.onclick = (e) => {
                        if (e.target === modal) {
                            closeModal(false);
                        }
                    };
                    
                    // ESC键关闭
                    const handleKeyDown = (e) => {
                        if (e.key === 'Escape') {
                            closeModal(false);
                            document.removeEventListener('keydown', handleKeyDown);
                        }
                    };
                    document.addEventListener('keydown', handleKeyDown);
                });
            }
            
            async deleteCurrentImage() {
                if (!this.currentImages || this.currentImages.length === 0) {
                    this.showMessage('没有图片可删除');
                    return;
                }
                
                const currentImage = this.currentImages[this.currentImageIndex];
                if (!currentImage || !currentImage.id) {
                    this.showMessage('无法获取图片信息');
                    return;
                }
                
                console.log('🗑️ 开始删除图片:', currentImage);
                
                // 显示自定义确认弹窗
                const confirmed = await this.showDeleteImageConfirm();
                if (!confirmed) return;
                
                try {
                    const response = await fetch(`/api/xhh/images/${currentImage.id}`, {
                        method: 'DELETE'
                    });
                    
                    console.log('🗑️ 删除图片响应状态:', response.status);
                    console.log('🗑️ 删除图片响应内容:', await response.text());
                    
                    if (response.ok) {
                        this.showMessage('图片已删除');
                        
                        // 从当前图片列表中移除
                        this.currentImages.splice(this.currentImageIndex, 1);
                        
                        // 如果删除后没有图片了，关闭模态框
                        if (this.currentImages.length === 0) {
                            const modal = document.querySelector('.image-gallery-modal');
                            if (modal) {
                                modal.remove();
                            }
                            this.showMessage('所有图片已删除');
                            return;
                        }
                        
                        // 调整当前索引
                        if (this.currentImageIndex >= this.currentImages.length) {
                            this.currentImageIndex = this.currentImages.length - 1;
                        }
                        
                        // 更新显示
                        this.updateMainImage();
                        this.updateThumbnailList();
                        
                    } else {
                        throw new Error('删除失败');
                    }
                } catch (error) {
                    console.error('删除图片失败:', error);
                    this.showMessage('删除失败: ' + error.message);
                }
            }
            
            showDeleteImageConfirm() {
                return new Promise((resolve) => {
                    // 创建确认弹窗
                    const modal = document.createElement('div');
                    modal.className = 'delete-confirm-modal';
                    modal.innerHTML = `
                        <div class="delete-confirm-content">
                            <div class="delete-confirm-icon">🗑️</div>
                            <div class="delete-confirm-title">确认删除图片</div>
                            <div class="delete-confirm-message">确定要删除这张图片吗？<br>删除后无法恢复。</div>
                            <div class="delete-confirm-buttons">
                                <button class="delete-confirm-btn cancel">取消</button>
                                <button class="delete-confirm-btn confirm">删除</button>
                            </div>
                        </div>
                    `;
                    
                    // 添加到页面
                    document.body.appendChild(modal);
                    
                    // 显示弹窗
                    setTimeout(() => {
                        modal.classList.add('show');
                    }, 10);
                    
                    // 绑定事件
                    const cancelBtn = modal.querySelector('.cancel');
                    const confirmBtn = modal.querySelector('.confirm');
                    
                    const closeModal = (result) => {
                        modal.classList.remove('show');
                        setTimeout(() => {
                            document.body.removeChild(modal);
                            resolve(result);
                        }, 300);
                    };
                    
                    cancelBtn.onclick = () => closeModal(false);
                    confirmBtn.onclick = () => closeModal(true);
                    
                    // 点击背景关闭
                    modal.onclick = (e) => {
                        if (e.target === modal) {
                            closeModal(false);
                        }
                    };
                    
                    // ESC键关闭
                    const handleKeyDown = (e) => {
                        if (e.key === 'Escape') {
                            closeModal(false);
                            document.removeEventListener('keydown', handleKeyDown);
                        }
                    };
                    document.addEventListener('keydown', handleKeyDown);
                });
            }
            
            updateThumbnailList() {
                const thumbnailList = document.getElementById('modalThumbnailList');
                if (!thumbnailList) return;
                
                thumbnailList.innerHTML = this.currentImages.map((img, index) => {
                    let thumbnailUrl;
                    if (img.thumbnail_url) {
                        thumbnailUrl = img.thumbnail_url;
                    } else if (img.file_path) {
                        thumbnailUrl = img.file_path;
                    } else if (typeof img === 'string') {
                        thumbnailUrl = img;
                    } else {
                        thumbnailUrl = '';
                    }
                    
                    return `
                        <div class="thumbnail-item ${index === this.currentImageIndex ? 'active' : ''}" 
                             data-index="${index}" onclick="promptManager.goToImage(${index})">
                            <img src="${thumbnailUrl}" alt="缩略图 ${index + 1}">
                        </div>
                    `;
                }).join('');
            }

            escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }

            formatTime(timestamp) {
                const date = new Date(timestamp);
                return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
            }

            showMessage(message) {
                // 简单的消息提示
                const toast = document.createElement('div');
                toast.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #4caf50;
                    color: white;
                    padding: 12px 20px;
                    border-radius: 4px;
                    z-index: 1000;
                    font-size: 14px;
                `;
                toast.textContent = message;
                document.body.appendChild(toast);
                
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 3000);
            }

             showError(message) {
                 const toast = document.createElement('div');
                 toast.style.cssText = `
                     position: fixed;
                     top: 20px;
                     right: 20px;
                     background: #f44336;
                     color: white;
                     padding: 12px 20px;
                     border-radius: 4px;
                     z-index: 1000;
                     font-size: 14px;
                 `;
                 toast.textContent = message;
                 document.body.appendChild(toast);
                 
                 setTimeout(() => {
                     document.body.removeChild(toast);
                 }, 5000);
             }
             
            showFullImage(imageUrl, promptId) {
                console.log("🖼️ 图片点击事件触发");
                console.log("  - imageUrl:", imageUrl);
                console.log("  - promptId:", promptId);
                
                // 获取提示词的所有图片
                this.getPromptImages(promptId || null).then(images => {
                    console.log("📸 获取到的图片列表:", images);
                    
                    if (images.length === 0) {
                        this.showMessage('该提示词没有图片');
                        return;
                    }
                    
                    this.currentImageIndex = images.findIndex(img => 
                        img.file_path === imageUrl || 
                        img.thumbnail_url === imageUrl || 
                        img.original_url === imageUrl
                    );
                    if (this.currentImageIndex === -1) this.currentImageIndex = 0;
                    
                    console.log("🎯 当前图片索引:", this.currentImageIndex);
                    
                    this.currentImages = images;
                    this.currentPromptId = promptId;
                    
                    // 使用统一的图片浏览界面
                    this.showPromptImageGallery(imageUrl, images, promptId);
                }).catch(error => {
                    console.error('获取图片列表失败:', error);
                    this.showMessage('获取图片列表失败');
                });
            }
            
            async getPromptImages(promptId) {
                console.log("🔍 获取提示词图片，promptId:", promptId);
                
                if (!promptId) {
                    // 如果没有指定提示词ID，返回所有提示词的图片
                    const allImages = [];
                    this.prompts.forEach(prompt => {
                        if (prompt.image_data) {
                            // 构造图片对象，包含缩略图和原图URL
                            allImages.push({
                                id: prompt.id,
                                filename: prompt.image_data.split('/').pop(),
                                file_path: prompt.image_data,
                                thumbnail_url: prompt.image_data,
                                original_url: prompt.original_image || prompt.image_data,
                                file_size: null,
                                width: null,
                                height: null,
                                mime_type: null
                            });
                        }
                        if (prompt.image_list && prompt.image_list.length > 0) {
                            prompt.image_list.forEach(img => {
                                allImages.push({
                                    id: prompt.id,
                                    filename: img.split('/').pop(),
                                    file_path: img,
                                    thumbnail_url: img,
                                    original_url: img,
                                    file_size: null,
                                    width: null,
                                    height: null,
                                    mime_type: null
                                });
                            });
                        }
                    });
                    console.log("📋 从所有提示词中获取图片:", allImages);
                    return allImages;
                }
                
                try {
                    console.log("🌐 请求API:", `/api/xhh/prompts/${promptId}/images`);
                    const response = await fetch(`/api/xhh/prompts/${promptId}/images`);
                    const data = await response.json();
                    console.log("📡 API响应:", data);
                    
                    if (data.success && data.data) {
                        // 保存提示词文本
                        if (data.prompt_text) {
                            this.currentPromptText = data.prompt_text;
                            console.log("💾 保存提示词文本:", this.currentPromptText);
                        }
                        
                        const images = data.data.map(img => {
                            console.log("🔍 处理图片对象:", img);
                            
                            // 返回完整的图片对象，包含所有URL信息
                            return {
                                id: img.id,
                                filename: img.filename,
                                file_path: img.file_path,
                                thumbnail_url: img.thumbnail_url,
                                original_url: img.original_url,
                                file_size: img.file_size,
                                width: img.width,
                                height: img.height,
                                mime_type: img.mime_type
                            };
                        });
                        console.log("🖼️ 转换后的图片路径:", images);
                        return images;
                    }
                    console.log("⚠️ API返回无数据");
                    return [];
                } catch (error) {
                    console.error('获取提示词图片失败:', error);
                    return [];
                }
            }
            
            showImageGallery() {
                const modal = document.getElementById('imageModal');
                const thumbnailList = document.getElementById('modalThumbnailList');
                // 确保获取模态框中的图片元素
                const mainImage = modal.querySelector('#modalMainImage');
                const imageCounter = document.getElementById('modalImageCounter');
                const promptText = document.getElementById('promptText');
                
                // 显示模态框
                modal.style.display = 'block';
                
                // 生成缩略图列表
                console.log("🖼️ 开始生成缩略图列表，图片数据:", this.currentImages);
                console.log("🖼️ 图片数据类型:", typeof this.currentImages);
                console.log("🖼️ 图片数据长度:", this.currentImages ? this.currentImages.length : 'undefined');
                
                thumbnailList.innerHTML = this.currentImages.map((img, index) => {
                    console.log(`🔍 处理缩略图 ${index}:`, img);
                    console.log(`🔍 图片对象类型:`, typeof img);
                    console.log(`🔍 图片对象键:`, Object.keys(img || {}));
                    
                    // 使用缩略图URL作为缩略图显示
                    let thumbnailUrl;
                    if (img.thumbnail_url) {
                        thumbnailUrl = img.thumbnail_url;
                        console.log(`✅ 使用 thumbnail_url:`, thumbnailUrl);
                    } else if (img.file_path) {
                        thumbnailUrl = img.file_path;
                        console.log(`✅ 使用 file_path:`, thumbnailUrl);
                    } else if (typeof img === 'string') {
                        thumbnailUrl = img;
                        console.log(`✅ 使用字符串:`, thumbnailUrl);
                    } else {
                        console.error(`❌ 缩略图 ${index} 没有有效的URL:`, img);
                        thumbnailUrl = ''; // 使用空字符串而不是对象
                    }
                    
                    console.log(`🖼️ 缩略图 ${index} 最终结果:`, {
                        original: img,
                        thumbnail_url: img.thumbnail_url,
                        file_path: img.file_path,
                        final_thumbnail: thumbnailUrl,
                        type: typeof thumbnailUrl
                    });
                    
                    const html = `
                        <div class="thumbnail-item ${index === this.currentImageIndex ? 'active' : ''}" 
                             data-index="${index}" onclick="promptManager.goToImage(${index})">
                            <img src="${thumbnailUrl}" alt="缩略图 ${index + 1}" onload="console.log('✅ 缩略图加载成功:', '${thumbnailUrl}')" onerror="console.error('❌ 缩略图加载失败:', '${thumbnailUrl}')">
                        </div>
                    `;
                    console.log(`🖼️ 缩略图 ${index} HTML:`, html);
                    return html;
                }).join('');
                console.log("🖼️ 缩略图列表生成完成，HTML长度:", thumbnailList.innerHTML.length);
                
                // 显示当前图片
                this.updateMainImage();
                
                // 更新提示词信息 - 使用API返回的prompt_text
                if (this.currentPromptText) {
                    promptText.textContent = this.currentPromptText;
                    this.currentPromptText = this.currentPromptText; // 保存到实例变量
                } else if (this.currentPromptId) {
                    const prompt = this.prompts.find(p => p.id == this.currentPromptId);
                    if (prompt) {
                        promptText.textContent = prompt.text;
                        this.currentPromptText = prompt.text; // 保存到实例变量
                    }
                }
                
                // 绑定事件
                this.bindGalleryEvents();
            }
            
            
            goToImage(index) {
                if (index >= 0 && index < this.currentImages.length) {
                    this.currentImageIndex = index;
                    this.updateMainImage();
                    this.scrollToActiveThumbnail();
                }
            }
            
            scrollToActiveThumbnail() {
                const thumbnailList = document.getElementById('modalThumbnailList');
                const activeThumbnail = thumbnailList.querySelector('.thumbnail-item.active');
                
                if (activeThumbnail && thumbnailList) {
                    const thumbnailHeight = 120 + 10; // thumbnail height + gap
                    const containerHeight = thumbnailList.clientHeight;
                    const thumbnailTop = activeThumbnail.offsetTop;
                    const thumbnailCenter = thumbnailTop + (thumbnailHeight / 2);
                    const containerCenter = containerHeight / 2;
                    
                    const scrollTop = thumbnailCenter - containerCenter;
                    
                    thumbnailList.scrollTo({
                        top: Math.max(0, scrollTop),
                        behavior: 'smooth'
                    });
                }
            }
            
            nextImage() {
                if (this.currentImageIndex < this.currentImages.length - 1) {
                    this.currentImageIndex++;
                    this.updateMainImage();
                }
            }
            
            prevImage() {
                if (this.currentImageIndex > 0) {
                    this.currentImageIndex--;
                    this.updateMainImage();
                }
            }
            
            bindGalleryEvents() {
                const modal = document.getElementById('imageModal');
                const closeBtn = document.getElementById('galleryClose');
                const prevBtn = document.getElementById('prevBtn');
                const nextBtn = document.getElementById('nextBtn');
                const thumbnailList = document.getElementById('modalThumbnailList');
                
                // 关闭按钮
                closeBtn.onclick = () => {
                    modal.style.display = 'none';
                };
                
                // 点击背景关闭
                modal.onclick = (event) => {
                    if (event.target === modal) {
                        modal.style.display = 'none';
                    }
                };
                
                // 导航按钮
                prevBtn.onclick = () => this.prevImage();
                nextBtn.onclick = () => this.nextImage();
                
                // 键盘导航
                document.addEventListener('keydown', (event) => {
                    if (modal.style.display === 'block') {
                        if (event.key === 'ArrowLeft') {
                            this.prevImage();
                        } else if (event.key === 'ArrowRight') {
                            this.nextImage();
                        } else if (event.key === 'Escape') {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                // 鼠标滚轮控制缩略图
                thumbnailList.addEventListener('wheel', (event) => {
                    event.preventDefault();
                    const delta = event.deltaY > 0 ? 1 : -1;
                    const newIndex = Math.max(0, Math.min(this.currentImages.length - 1, this.currentImageIndex + delta));
                    if (newIndex !== this.currentImageIndex) {
                        this.goToImage(newIndex);
                    }
                });
            }
            
            showPromptImageGallery(imageUrl, images, promptId) {
                console.log("🎯 显示提示词图片浏览界面");
                console.log("  - imageUrl:", imageUrl);
                console.log("  - images:", images);
                console.log("  - promptId:", promptId);
            
                if (!images || images.length === 0) {
                    console.log("❌ 没有图片数据");
                    this.showMessage('该提示词没有图片');
                    return;
                }
                
                // 设置当前图片数组
                this.currentImages = images;
                this.currentPromptId = promptId || null;
                
                // 找到当前图片在列表中的索引
                this.currentImageIndex = images.findIndex(img => img === imageUrl);
                console.log("🔍 图片匹配结果:", {
                    imageUrl: imageUrl,
                    images: images,
                    foundIndex: this.currentImageIndex
                });
                
                if (this.currentImageIndex === -1) {
                    console.log("⚠️ 未找到匹配的图片，使用第一张图片");
                    this.currentImageIndex = 0;
                }
                
                console.log("📋 最终设置:", {
                    currentImageIndex: this.currentImageIndex,
                    currentImages: this.currentImages,
                    currentPromptId: this.currentPromptId
                });
                
                this.showPromptImageGalleryModal();
            }
            
            showPromptImageGalleryModal() {
                // 创建图片浏览模态框
                const modal = document.createElement('div');
                modal.className = 'image-gallery-modal';
                modal.innerHTML = `
                    <div class="gallery-header">
                        <h3 id="galleryTitle">提示词图片浏览</h3>
                        <span class="gallery-close" id="galleryClose">&times;</span>
                    </div>
                    <div class="gallery-container">
                        <!-- 左侧缩略图列表 -->
                        <div class="thumbnail-sidebar">
                            <div class="thumbnail-list" id="modalThumbnailList">
                                <!-- 缩略图将在这里动态生成 -->
                            </div>
                        </div>
                        
                        <!-- 中间主图片区域 -->
                        <div class="main-image-area">
                            <button class="nav-btn prev-btn" id="prevBtn">‹</button>
                            <div class="image-display" id="modalImageDisplay">
                                <img id="modalMainImage" class="main-image" src="" alt="">
                                <div class="image-info">
                                    <span id="modalImageCounter">1 / 1</span>
                                    <button class="delete-image-btn" id="deleteImageBtn" onclick="promptManager.deleteCurrentImage()" title="删除当前图片">🗑️</button>
                                </div>
                                <!-- 模式切换按钮 -->
                                <div class="mode-controls">
                                    <button class="mode-btn active" id="scrollModeBtn" onclick="promptManager.setMode('scroll')">滚动模式</button>
                                    <button class="mode-btn" id="manualModeBtn" onclick="promptManager.setMode('manual')">手动模式</button>
                                </div>
                            </div>
                            <button class="nav-btn next-btn" id="nextBtn">›</button>
                        </div>
                        
                        <!-- 右侧提示词信息 -->
                        <div class="prompt-info-sidebar">
                            <h4>提示词信息</h4>
                            <div id="promptInfo" class="prompt-info"></div>
                            
                            <h4 style="margin-top: 20px;">当前图片提示词</h4>
                            <div id="currentPromptInfo" class="prompt-info">
                                <div class="prompt-text" id="currentPromptText">暂无提示词信息</div>
                                <button class="copy-btn" id="copyPromptBtn" onclick="promptManager.copyPrompt()">复制提示词</button>
                            </div>
                        </div>
                    </div>
                `;
            
                // 添加到页面
                document.body.appendChild(modal);
                
                // 显示模态框
                modal.style.display = 'block';
                
                // 生成缩略图列表
                const thumbnailList = document.getElementById('modalThumbnailList');
                console.log("🖼️ 生成缩略图列表，图片数组:", this.currentImages);
                console.log("🖼️ 图片数据类型:", typeof this.currentImages);
                console.log("🖼️ 图片数据长度:", this.currentImages ? this.currentImages.length : 'undefined');
                
                thumbnailList.innerHTML = this.currentImages.map((img, index) => {
                    console.log(`🔍 处理缩略图 ${index}:`, img);
                    console.log(`🔍 图片对象类型:`, typeof img);
                    console.log(`🔍 图片对象键:`, Object.keys(img || {}));
                    
                    // 使用缩略图URL作为缩略图显示
                    let thumbnailUrl;
                    if (img.thumbnail_url) {
                        thumbnailUrl = img.thumbnail_url;
                        console.log(`✅ 使用 thumbnail_url:`, thumbnailUrl);
                    } else if (img.file_path) {
                        thumbnailUrl = img.file_path;
                        console.log(`✅ 使用 file_path:`, thumbnailUrl);
                    } else if (typeof img === 'string') {
                        thumbnailUrl = img;
                        console.log(`✅ 使用字符串:`, thumbnailUrl);
                    } else {
                        console.error(`❌ 缩略图 ${index} 没有有效的URL:`, img);
                        thumbnailUrl = ''; // 使用空字符串而不是对象
                    }
                    
                    console.log(`🖼️ 缩略图 ${index} 最终结果:`, {
                        original: img,
                        thumbnail_url: img.thumbnail_url,
                        file_path: img.file_path,
                        final_thumbnail: thumbnailUrl,
                        type: typeof thumbnailUrl
                    });
                    
                    return `
                        <div class="thumbnail-item ${index === this.currentImageIndex ? 'active' : ''}" 
                             data-index="${index}" onclick="promptManager.goToImage(${index})">
                            <img src="${thumbnailUrl}" alt="缩略图 ${index + 1}" onload="console.log('✅ 缩略图加载成功:', '${thumbnailUrl}')" onerror="console.error('❌ 缩略图加载失败:', '${thumbnailUrl}')">
                        </div>
                    `;
                }).join('');
                
                console.log("🖼️ 缩略图HTML生成完成");
                
                // 显示当前图片
                console.log("🖼️ 准备更新主图片");
                this.updateMainImage();
                
                // 更新提示词信息
                if (this.currentPromptId) {
                    const prompt = this.prompts.find(p => p.id === this.currentPromptId);
                    if (prompt) {
                        const promptInfo = document.getElementById('promptInfo');
                        promptInfo.innerHTML = `
                            <div><strong>ID:</strong> ${prompt.id}</div>
                            <div><strong>创建时间:</strong> ${prompt.created_at}</div>
                            <div><strong>收藏:</strong> ${prompt.is_favorite ? '是' : '否'}</div>
                            <div><strong>来源:</strong> ${prompt.source}</div>
                        `;
                    }
                }
                
                // 绑定事件
                this.bindPromptGalleryEvents(modal);
                
                // 初始化图片交互事件
                setTimeout(() => {
                    this.initImageInteractions();
                }, 100);
            }
            
            updateMainImage() {
                // 优先查找模态框中的图片元素
                const modal = document.getElementById('imageModal');
                let mainImage = null;
                
                if (modal) {
                    mainImage = modal.querySelector('#modalMainImage');
                }
                
                // 如果模态框中没有找到，使用其他方法
                if (!mainImage) {
                    mainImage = document.getElementById('modalMainImage');
                }
                if (!mainImage) {
                    mainImage = document.querySelector('.main-image');
                }
                if (!mainImage) {
                    mainImage = document.querySelector('img[id="modalMainImage"]');
                }
                if (!mainImage) {
                    mainImage = document.querySelector('#modalMainImage');
                }
                
                const imageCounter = document.getElementById('modalImageCounter');
                const currentImage = this.currentImages[this.currentImageIndex];
                
                console.log("🖼️ 更新主图片:", currentImage);
                console.log("🖼️ 当前图片数组:", this.currentImages);
                console.log("🖼️ 当前索引:", this.currentImageIndex);
                console.log("🔍 找到的图片元素:", mainImage);
                
                if (!mainImage) {
                    console.error("❌ 无法找到图片元素！");
                    return;
                }
                
                if (mainImage && imageCounter) {
                    if (currentImage) {
                        // 优先使用原图URL，如果不存在则使用缩略图URL，最后使用file_path
                        let displayUrl = currentImage.original_url;
                        if (!displayUrl || displayUrl === currentImage.thumbnail_url) {
                            displayUrl = currentImage.thumbnail_url;
                        }
                        if (!displayUrl) {
                            displayUrl = currentImage.file_path;
                        }
                        
                        console.log("🖼️ 主图设置:", {
                            currentImage: currentImage,
                            original_url: currentImage.original_url,
                            thumbnail_url: currentImage.thumbnail_url,
                            file_path: currentImage.file_path,
                            final_display: displayUrl
                        });
                        
                        // 强制设置图片源，使用多种方法
                        mainImage.setAttribute('src', displayUrl);
                        mainImage.src = displayUrl;
                        
                        // 添加图片加载事件监听
                        mainImage.onload = () => {
                            console.log("✅ 图片加载成功:", displayUrl);
                            console.log("📏 图片尺寸:", mainImage.naturalWidth, "x", mainImage.naturalHeight);
                        };
                        
                        mainImage.onerror = (e) => {
                            console.error("❌ 图片加载失败:", displayUrl, e);
                            console.log("🔄 尝试使用缩略图URL");
                            // 如果原图加载失败，尝试使用缩略图
                            if (displayUrl !== currentImage.thumbnail_url && currentImage.thumbnail_url) {
                                console.log("🔄 使用缩略图URL:", currentImage.thumbnail_url);
                                mainImage.src = currentImage.thumbnail_url;
                            } else {
                                console.log("🔄 使用测试图片");
                                mainImage.src = "";
                            }
                        };
                        
                        mainImage.src = displayUrl;
                        
                        // 再次强制设置，确保图片被正确设置
                        setTimeout(() => {
                            if (mainImage.src !== displayUrl) {
                                console.log("🔄 重新设置图片源");
                                mainImage.src = displayUrl;
                            }
                        }, 50);
                        
                        // 延迟检查图片状态
                        setTimeout(() => {
                            console.log("🔍 图片状态检查:", {
                                src: mainImage.src,
                                complete: mainImage.complete,
                                naturalWidth: mainImage.naturalWidth,
                                naturalHeight: mainImage.naturalHeight,
                                offsetWidth: mainImage.offsetWidth,
                                offsetHeight: mainImage.offsetHeight,
                                style: {
                                    display: getComputedStyle(mainImage).display,
                                    visibility: getComputedStyle(mainImage).visibility,
                                    opacity: getComputedStyle(mainImage).opacity
                                }
                            });
                            
                            // 检查图片是否被清空
                            if (!mainImage.src || mainImage.src === '') {
                                console.error("❌ 图片src被清空了！");
                                mainImage.src = displayUrl;
                            }
                        }, 200);
                    } else {
                        console.log("⚠️ 当前图片为空，使用测试图片");
                        // 使用一个测试图片
                        mainImage.src = "";
                    }
                    
                    imageCounter.textContent = `${this.currentImageIndex + 1} / ${this.currentImages.length}`;
                    
                    // 更新缩略图选中状态
                    document.querySelectorAll('.thumbnail-item').forEach((item, index) => {
                        item.classList.toggle('active', index === this.currentImageIndex);
                    });
                    
                    // 更新提示词信息 - 直接使用已有的prompt_text
                    this.updatePromptText();
                } else {
                    console.error("❌ 图片设置失败:", {
                        mainImage: !!mainImage,
                        imageCounter: !!imageCounter,
                        currentImage: currentImage,
                        currentImages: this.currentImages
                    });
                }
            }
            
            updatePromptText() {
                // 直接使用已有的prompt_text，不需要额外的API请求
                const promptText = document.getElementById('currentPromptText');
                const copyBtn = document.getElementById('copyPromptBtn');
                
                if (this.currentPromptText) {
                    promptText.textContent = this.currentPromptText;
                    copyBtn.style.display = 'block';
                    console.log("✅ 使用已有的提示词文本:", this.currentPromptText);
                } else {
                    promptText.textContent = '暂无提示词信息';
                    copyBtn.style.display = 'none';
                    console.log("⚠️ 没有可用的提示词文本");
                }
            }
            
            copyPrompt() {
                const promptText = document.getElementById('currentPromptText');
                const text = promptText.textContent;
                
                if (text && text !== '暂无提示词信息' && text !== '获取提示词信息失败') {
                    navigator.clipboard.writeText(text).then(() => {
                        // 显示复制成功提示
                        const copyBtn = document.getElementById('copyPromptBtn');
                        const originalText = copyBtn.textContent;
                        copyBtn.textContent = '已复制!';
                        copyBtn.style.background = '#28a745';
                        
                        setTimeout(() => {
                            copyBtn.textContent = originalText;
                            copyBtn.style.background = '#667eea';
                        }, 2000);
                    }).catch(err => {
                        console.error('复制失败:', err);
                        alert('复制失败，请手动复制');
                    });
                }
            }
            
            // 设置图片浏览模式
            setMode(mode) {
                const imageDisplay = document.getElementById('modalImageDisplay');
                const mainImage = document.getElementById('modalMainImage');
                const scrollBtn = document.getElementById('scrollModeBtn');
                const manualBtn = document.getElementById('manualModeBtn');
                
                // 更新按钮状态
                scrollBtn.classList.toggle('active', mode === 'scroll');
                manualBtn.classList.toggle('active', mode === 'manual');
                
                // 更新显示模式
                imageDisplay.classList.toggle('manual-mode', mode === 'manual');
                
                if (mode === 'scroll') {
                    // 滚动模式：恢复默认状态
                    mainImage.classList.remove('zoomed');
                    mainImage.style.transform = '';
                    mainImage.style.cursor = 'default';
                } else {
                    // 手动模式：启用缩放和拖拽
                    mainImage.style.cursor = 'zoom-in';
                }
                
                console.log(`🔄 切换到${mode === 'scroll' ? '滚动' : '手动'}模式`);
                
                // 在滚动模式下，确保图片可以正常切换
                if (mode === 'scroll') {
                    console.log('📸 滚动模式已激活，可以使用鼠标滚轮切换图片');
                }
            }
            
            // 初始化图片交互事件
            initImageInteractions() {
                const mainImage = document.getElementById('modalMainImage');
                const imageDisplay = document.getElementById('modalImageDisplay');
                
                if (!mainImage || !imageDisplay) return;
                
                let isZoomed = false;
                let isDragging = false;
                let startX = 0;
                let startY = 0;
                let translateX = 0;
                let translateY = 0;
                
                // 点击切换缩放
                mainImage.addEventListener('click', (e) => {
                    if (imageDisplay.classList.contains('manual-mode')) {
                        e.preventDefault();
                        isZoomed = !isZoomed;
                        mainImage.classList.toggle('zoomed', isZoomed);
                        mainImage.style.cursor = isZoomed ? 'zoom-out' : 'zoom-in';
                        
                        if (!isZoomed) {
                            // 重置位置
                            mainImage.style.transform = '';
                            translateX = 0;
                            translateY = 0;
                        }
                    }
                });
                
                // 拖拽功能
                mainImage.addEventListener('mousedown', (e) => {
                    if (imageDisplay.classList.contains('manual-mode') && isZoomed) {
                        e.preventDefault();
                        isDragging = true;
                        startX = e.clientX - translateX;
                        startY = e.clientY - translateY;
                        mainImage.style.cursor = 'grabbing';
                    }
                });
                
                document.addEventListener('mousemove', (e) => {
                    if (isDragging && isZoomed) {
                        e.preventDefault();
                        translateX = e.clientX - startX;
                        translateY = e.clientY - startY;
                        mainImage.style.transform = `scale(1.5) translate(${translateX}px, ${translateY}px)`;
                    }
                });
                
                document.addEventListener('mouseup', () => {
                    if (isDragging) {
                        isDragging = false;
                        mainImage.style.cursor = isZoomed ? 'zoom-out' : 'zoom-in';
                    }
                });
                
                // 鼠标滚轮事件
                imageDisplay.addEventListener('wheel', (e) => {
                    if (imageDisplay.classList.contains('manual-mode')) {
                        // 手动模式：缩放功能
                        e.preventDefault();
                        const delta = e.deltaY > 0 ? 0.9 : 1.1;
                        const currentScale = isZoomed ? 1.5 : 1;
                        const newScale = Math.max(0.5, Math.min(3, currentScale * delta));
                        
                        if (newScale > 1.1) {
                            isZoomed = true;
                            mainImage.classList.add('zoomed');
                            mainImage.style.cursor = 'zoom-out';
                        } else {
                            isZoomed = false;
                            mainImage.classList.remove('zoomed');
                            mainImage.style.cursor = 'zoom-in';
                            translateX = 0;
                            translateY = 0;
                        }
                        
                        mainImage.style.transform = `scale(${newScale}) translate(${translateX}px, ${translateY}px)`;
                    } else {
                        // 滚动模式：切换图片
                        e.preventDefault();
                        console.log('🖱️ 滚动模式滚轮事件:', e.deltaY);
                        if (e.deltaY > 0) {
                            // 向下滚动，显示下一张图片
                            console.log('📸 向下滚动，显示下一张图片');
                            this.nextImage();
                        } else {
                            // 向上滚动，显示上一张图片
                            console.log('📸 向上滚动，显示上一张图片');
                            this.prevImage();
                        }
                    }
                });
            }
            
            goToImage(index) {
                if (index >= 0 && index < this.currentImages.length) {
                    this.currentImageIndex = index;
                    this.updateMainImage();
                    this.scrollToActiveThumbnail();
                }
            }
            
            scrollToActiveThumbnail() {
                const thumbnailList = document.getElementById('modalThumbnailList');
                const activeThumbnail = thumbnailList.querySelector('.thumbnail-item.active');
                
                if (activeThumbnail && thumbnailList) {
                    const thumbnailHeight = 120 + 10; // thumbnail height + gap
                    const containerHeight = thumbnailList.clientHeight;
                    const thumbnailTop = activeThumbnail.offsetTop;
                    const thumbnailCenter = thumbnailTop + (thumbnailHeight / 2);
                    const containerCenter = containerHeight / 2;
                    
                    const scrollTop = thumbnailCenter - containerCenter;
                    
                    thumbnailList.scrollTo({
                        top: Math.max(0, scrollTop),
                        behavior: 'smooth'
                    });
                }
            }
            
            nextImage() {
                console.log('📸 切换到下一张图片，当前索引:', this.currentImageIndex, '总数量:', this.currentImages.length);
                this.currentImageIndex = (this.currentImageIndex + 1) % this.currentImages.length;
                console.log('📸 新索引:', this.currentImageIndex);
                this.updateMainImage();
                this.scrollToActiveThumbnail();
            }
            
            prevImage() {
                console.log('📸 切换到上一张图片，当前索引:', this.currentImageIndex, '总数量:', this.currentImages.length);
                this.currentImageIndex = (this.currentImageIndex - 1 + this.currentImages.length) % this.currentImages.length;
                console.log('📸 新索引:', this.currentImageIndex);
                this.updateMainImage();
                this.scrollToActiveThumbnail();
            }
            
            bindPromptGalleryEvents(modal) {
                const closeBtn = document.getElementById('galleryClose');
                const prevBtn = document.getElementById('prevBtn');
                const nextBtn = document.getElementById('nextBtn');
                const thumbnailList = document.getElementById('modalThumbnailList');
                
                // 关闭按钮
                closeBtn.onclick = () => {
                    modal.remove();
                };
                
                // 点击背景关闭
                modal.onclick = (event) => {
                    if (event.target === modal) {
                        modal.remove();
                    }
                };
                
                // ESC键关闭
                const handleKeyDown = (event) => {
                    if (event.key === 'Escape') {
                        modal.remove();
                        document.removeEventListener('keydown', handleKeyDown);
                    }
                };
                document.addEventListener('keydown', handleKeyDown);
                
                // 导航按钮
                prevBtn.onclick = () => this.prevImage();
                nextBtn.onclick = () => this.nextImage();
                
                // 键盘导航
                const keyHandler = (event) => {
                    if (modal.parentNode) {
                        if (event.key === 'ArrowLeft') {
                            this.prevImage();
                        } else if (event.key === 'ArrowRight') {
                            this.nextImage();
                        } else if (event.key === 'Escape') {
                            modal.remove();
                        }
                    }
                };
                
                document.addEventListener('keydown', keyHandler);
                
                // 清理事件监听器
                modal.addEventListener('remove', () => {
                    document.removeEventListener('keydown', keyHandler);
                });
                
                // 缩略图列表滚轮事件
                if (thumbnailList) {
                    thumbnailList.addEventListener('wheel', (event) => {
                        event.preventDefault();
                        if (event.deltaY > 0) {
                            this.nextImage();
                        } else {
                            this.prevImage();
                        }
                    });
                }
            }
        }

        // 初始化提示词管理器
        const promptManager = new PromptManager();
    </script>
</body>
</html>